package org.kzwl.service.app.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.kzwl.comm.advice.BizException;
import org.kzwl.entity.app.Verification;
import org.kzwl.mapper.app.VerificationMapper;
import org.kzwl.service.app.VerificationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class VerificationServiceImpl extends ServiceImpl<VerificationMapper, Verification> implements VerificationService {

    @Autowired
    private VerificationMapper verificationMapper;

    @Override
    public void insetCode(String phone, String code) {
        QueryWrapper<Verification> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Verification::getCuVerificationExt, phone).eq(Verification::getCuVerificationState, 0);

        Verification verification = verificationMapper.selectOne(queryWrapper);
        if (verification != null) {
            verification.setCuVerificationCode(code);
            verificationMapper.updateById(verification);
            return;
        }
        verification = new Verification();
        verification.setCuVerificationCode(code);
        verification.setCuVerificationExt(phone);
        verificationMapper.insert(verification);
    }

    @Override
    public void updateCode(String phone, String code) {
        QueryWrapper<Verification> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Verification::getCuVerificationExt, phone).eq(Verification::getCuVerificationState, 0).eq(Verification::getCuVerificationCode, code);
        Verification verification = verificationMapper.selectOne(queryWrapper);
        if (verification == null) {
            throw new BizException("验证码已过期");
        }
        verification.setCuVerificationState(1);
        verificationMapper.updateById(verification);
    }

    @Override
    public void setCode(String phone, String code) {

    }

    @Override
    public Verification getCode(String phone) {
        QueryWrapper<Verification> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Verification::getCuVerificationExt, phone).eq(Verification::getCuVerificationState, 0);
        Verification verification = verificationMapper.selectOne(queryWrapper);
        if (verification == null){
            throw new BizException("验证码过期或错误");
        }
        return verification;
    }

}
